#include <LPC22xx.h>
#include "uart2.h"
#include <string.h>

int UART2BufferCount;
char UART2Buffer[500];

void UART2_IRQHandler (void) __irq 
{
	// read all data
	while( U1LSR & 0x01 )
	{
		unsigned char data = U1RBR;
		UART2Buffer[UART2BufferCount] = data;
		if(UART2BufferCount<(500-1)) UART2BufferCount++;
	}

	VICVectAddr = 0;                      /* Acknowledge Interrupt              */	
}

void UART2Driver::Init()
{	
	UART2BufferCount = 0;

	// set UART pins
	PINSEL0 |= 0x00050000; // set UART1 TXD and RXD
	
	// set 8N1 + activate divisor latch
	U1LCR = 0x83;   /* 8 bits, no Parity, 1 Stop bit */
	// set baud rate 19200 -> pclk = 16MHz
	U1DLM = 0; //MSB	 
	U1DLL = 0xC3; //LSB
	//U0FDR=0x00000000;
	// remove divisor latch
	U1LCR = 0x03;
	// activate FIFO
	U1FCR = 0x47;	// 14 bytes fifo + enable + reset + int on 4 bytes in FIFO
	
	// set interrupts			 VICVectCntl is used as 10, because of priority: (0-highest, 15-lowest)
	VICVectCntl11  = 32 + 7;                          /* enable and set ID to 6 (uart0 int) */
	VICVectAddr11  = (unsigned long)UART2_IRQHandler;/* Set Interrupt Vector        */
	VICIntEnable  |= (1 << 7);                   /* Enable Uart0 Interrupt     */
	U1IER = 0x00000001;		// enable RX int
}			 

void UART2Driver::SendChar(char ch)
{
	while( !(U1LSR & 0x20) ); // wait for tx is cleared
	U1THR = ch;
}
									
void UART2Driver::SendData(char* buffer)
{
	SendData(buffer, strlen(buffer));
}    

void UART2Driver::SendData(char* buffer, int length)
{
	for(int i=0; i!= length; i++)
	{
		SendChar(*buffer);
		buffer++;
	}
}

int UART2Driver::ReceiveCommand(char* buffer) // returns message length
{
	int count;
	VICIntEnClr |= (1 << 7);
	memcpy(buffer, UART2Buffer, UART2BufferCount);
	count = UART2BufferCount;
	UART2BufferCount = 0; 
	VICIntEnable |= (1 << 7);

	return count;
}
